package com.zrb.mobile;
 
import java.util.ArrayList;
import org.apache.http.Header;

 
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
 
import com.zrb.mobile.adapter.Project_comments_listAdapter;
import com.zrb.mobile.adapter.Project_comments_listAdapter.onCommentListener;
import com.zrb.mobile.adapter.model.ProCommentDto;
import com.zrb.mobile.adapter.model.ProCommentDtos;
import com.zrb.mobile.adapter.model.UserDtos;
import com.zrb.mobile.pulltorefresh.PullToRefreshBase;
import com.zrb.mobile.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.zrb.mobile.register.User_phone_login;
import com.zrb.mobile.ui.CustomloadingView;
import com.zrb.mobile.ui.PullToRefreshListViewEx;
import com.zrb.mobile.ui.onLoadMoreListener;
 
import com.zrb.applib.utils.AppSetting;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.ZrbRestClient;

import android.os.Bundle;
import android.os.Handler;
import android.content.Intent;
import android.text.format.DateUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class Project_commentlist_Activity extends BaseActivity implements OnClickListener, onCommentListener, onLoadMoreListener{
  
	PullToRefreshListViewEx msearchResults;
	Project_comments_listAdapter mcommentAdapter;
	//SearchResultAdapter mInputsAdapter;
	int maxid;
	int currentPage =1,projectId;
	CustomloadingView loadingview;
	int pageSize=10;
	Handler mhandler = new Handler();
    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.project_commentlist);
        if (bundle != null)
			restoreSelf(bundle);
		else {
 			projectId = this.getIntent().getIntExtra("projectId", -1);
			maxid = this.getIntent().getIntExtra("maxid", -1);
		}
        initview();
        LoadData(maxid,false);
     }
    
    @Override
	protected  void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("projectId", projectId);
        outState.putInt("maxid", maxid);
    }
    
    private void restoreSelf(Bundle savedInstanceState){
	   projectId = savedInstanceState.getInt("projectId", -1); 
	   maxid = savedInstanceState.getInt("maxid", -1); 
    } 
    
    private void initview(){
     	TextView txtTitle=	(TextView)this.findViewById(R.id.txt_title);
		txtTitle.setText("��������");
		txtTitle.setOnClickListener(this);
		
		ImageView rightbtn=	(ImageView)this.findViewById(R.id.img_right_icon);
		rightbtn.setVisibility(View.VISIBLE);
		rightbtn.setImageResource(R.drawable.project_bar_comment);
		rightbtn.setOnClickListener(this);
		
		View lefticon= this.findViewById(R.id.title_left_root);
		lefticon.setOnClickListener(this);
    	
    	loadingview=(CustomloadingView)this.findViewById(R.id.list_emptyview);
    	loadingview.Hide();
 		msearchResults=(PullToRefreshListViewEx)this.findViewById(R.id.search_result_list_view);
 		msearchResults.setPagesize(pageSize);
  		// Set a listener to be invoked when the list should be refreshed.
		msearchResults.setOnRefreshListener(new OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(PullToRefreshBase<ListView> refreshView) {
						String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
								DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

						// Update the LastUpdatedLabel
						refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
 						//currentPage++;
						//LoadData(mcommentAdapter.getMinId());
						currentPage =1;
						mhandler.postDelayed(new Runnable(){
				             @Override
				            public void run() {
				            	 LoadData(maxid,true);
				            }
				         }, 1000);
 					}
				});
		mcommentAdapter=new Project_comments_listAdapter(this,new ArrayList<ProCommentDto>()); 
		mcommentAdapter.setOnCommentListener(this);
		msearchResults.initAdapter(mcommentAdapter);
		msearchResults.setOnLoadMoreListener(this);
     }
     
    @Override
	public void OnLoadMoreEvent() {
		// TODO Auto-generated method stub
    	currentPage++;
    	mhandler.postDelayed(new Runnable(){
             @Override
            public void run() {
            	 LoadData(mcommentAdapter.getMinId(),false);
            }
         }, 1000);
 	}
    
    private void LoadData(int curid,final boolean isRefresh)
	{
    	RequestParams param = new RequestParams();
    	if(curid!=-1) param.put("maxCommentId",curid);
      	if(currentPage==1&&!isRefresh){ 
    		loadingview.HideText("��������С���").ShowLoading();
    	}  
     	param.put("pid",projectId);
      	param.put("zrb_front_ut", AppSetting.curUser==null? "":AppSetting.curUser.zrb_front_ut);
        param.put("limit",pageSize); 
        
        CommonUtil.InfoLog("projectComment", param.toString());
  		ZrbRestClient.post("projectComment/query", param,  new AsyncHttpResponseHandler()
    	{
 			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
 				msearchResults.onRefreshComplete();
 				  if(currentPage==1)
 					 loadingview.HideText("������ݳ��?").ShowRefleshBtn(true).ShowError();
				  else
		   	         CommonUtil.showToast("������ݳ��?", Project_commentlist_Activity.this);
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
 				String results=new String(arg2);
 				msearchResults.onRefreshComplete();
 			    if(currentPage==1&&!isRefresh)  loadingview.Hide();;
 			    if(currentPage>1) msearchResults.hideloading();
				try 
				{
 					Gson gson = new Gson();  
					ProCommentDtos tmpDto=	gson.fromJson(results, ProCommentDtos.class);  
 			        if(tmpDto.res==1) {
 	                	if(tmpDto.data!=null&&tmpDto.data.size()>0){
	                	   if(currentPage==1)  
	                		   mcommentAdapter.setDatas(tmpDto.data);
 	                	   else   
 	                		   mcommentAdapter.addAll(tmpDto.data);
 	                	   mcommentAdapter.notifyDataSetChanged();
 	                	}
	                	else
	                	  if(currentPage==1) loadingview.HideText("��������").ShowNull();
  			       }
 			       else CommonUtil.showToast(tmpDto.msg, Project_commentlist_Activity.this);
      			}
				catch(Exception e){
					 CommonUtil.showToast("error:������ݳ��?", Project_commentlist_Activity.this);
				}
  			}});
  	
	}

	@Override
	protected void	onActivityResult(int requestCode, int resultCode, Intent data){
 	    if(resultCode==RESULT_OK){
		  switch (requestCode) { // resultCodeΪ�ش��ı�ǣ�����B�лش�����RESULT_OK
 		    case 200:
 		    	 if(!mcommentAdapter.isEmpty()){
 		    		 msearchResults.setRefreshing(true);
 		    	 }else
 		    	   LoadData(maxid,false);
 		    	 
				  break;
  		    default:
			 break;
		  }
 	    }
 	    super.onActivityResult(requestCode, resultCode, data);
   } 
    
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		  case R.id.title_left_root:
 			  this.finish();
 		      break;
		  case R.id.img_right_icon:
 			  Intent it = new Intent(this, Project_commentActivity.class);
 			  it.putExtra("projectId", projectId);
 			  this.startActivityForResult(it, 200);
  	 	    //  startActivity(it);
 			  break;
		  case R.id.searchButton:
//			  Intent it = new Intent(this, Search_resultActivity.class);
//		 	  startActivity(it);
//		 	  this.finish();
			 // seachkeywords(true);
			  break;
		  case R.id.go_to_hot_image_view:
			//  mSearchText.setText("");
			  break;
		  case  R.id.txt_title:
			 
			  msearchResults.setRefreshing(true);
		      break;
		}
	}
 
	
	/*@Override
	protected void	onActivityResult(int requestCode, int resultCode, Intent data){
 	    if(resultCode==RESULT_OK){
		  switch (requestCode) { // resultCodeΪ�ش��ı�ǣ�����B�лش�����RESULT_OK
  		    case 100:
		       Intent it2 = new Intent(Project_commentlist_Activity.this, Project_commentActivity.class);
		       it2.putExtra("projectId", projectId);
			   startActivity(it2);
			   break;
 		    default:
			break;
		  }
 	    }
 	    super.onActivityResult(requestCode, resultCode, data);
   } */
	
	
	//type 1,del 2 reply
	@Override
	public void onReply(int postion, int type) {
		// TODO Auto-generated method stub
		if(type==1) deleteComment(postion);
		else{
 			 if( null != AppSetting.curUser){
  				 ProCommentDto curDto=mcommentAdapter.getCurItem(postion);
  				 
  				 Intent it4 = new Intent(Project_commentlist_Activity.this, Project_commentActivity.class);
				 it4.putExtra("projectId", projectId);
				 it4.putExtra("targetId", curDto.getUid());
				 it4.putExtra("targetName", curDto.getUname());
			   //  startActivity(it4);
			     this.startActivityForResult(it4, 200);
			 }else{
				 Intent it = new Intent(this, User_phone_login.class);
		 		 it.putExtra("forResult", true);
				 this.startActivityForResult(it,100);
	 		 }
		}
 	}
 	
	  private void deleteComment(final int postion){
			//projectComment/remove?id=4&zrb_front_ut=0f4ec09bca0783621edbfaf1cbba63dd
		  
		    ProCommentDto curDto=  mcommentAdapter.getCurItem(postion);
		    
			RequestParams param = new RequestParams();
 	    	param.put("id",curDto.getId());
 	    	param.put("pid",projectId);
	    	param.put("zrb_front_ut", AppSetting.curUser.zrb_front_ut);
	    	ZrbRestClient.post("projectComment/remove" , param,
					new AsyncHttpResponseHandler() {

						@Override
						public void onFailure(int arg0, Header[] arg1, byte[] arg2,
								Throwable arg3) {
							CommonUtil.showToast("���糬ʱ,����������", Project_commentlist_Activity.this);
						}

						@Override
						public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
							// TODO Auto-generated method stub
							String results = new String(arg2);
							//Log.e("tag", results);
							try {
								Gson gson = new Gson();
								UserDtos tmpDto = gson.fromJson(results,UserDtos.class);
								if(tmpDto.res==1){
									CommonUtil.showToast("ɾ��ɹ�", Project_commentlist_Activity.this);
 									mcommentAdapter.removeAtIndex(postion);
								}
								else 
								   CommonUtil.showToast("�����쳣�������³���", Project_commentlist_Activity.this);
						 		 
						     } catch (Exception e) {
 							     CommonUtil.showToast( "fail:"+e.getMessage(),Project_commentlist_Activity.this);
								System.out.println("eeee!!!!" + e.getMessage());
 							}

						}
					});
		}

	
}
